import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    userMessage: '',
    headTag: [],
    closeShow: false
  },
  mutations: {
    setUserMessage(state, userMsg) {
      state.userMessage = userMsg;
      localStorage.userMsg = JSON.stringify(userMsg);
    },
    setHeadTag(state, router) {
      if(state.headTag.length === 0) {
        state.headTag.push(router);
      }
      if(state.headTag.length > 10) {
        state.headTag.shift();
      }
      state.closeShow = true;
      function filter(arr,item) {
        for(let i = 0; i < arr.length; i++) {
          if(arr[i].index === item.index) {
            return true;
          }
        }
        return false;
      }
      if(!filter(state.headTag, router)) {
        state.headTag.push(router);
        localStorage.router = JSON.stringify(state.headTag);
      }
    },
    romveTag(state, router) {
      if(router === 'closeAll') {
        localStorage.removeItem('router');
        state.headTag = [];
        state.closeShow = false;
        return;
      }
      function filter(arr,item) {
        console.log(arr)
        for(let i = 0; i < arr.length; i++) {
          if(arr[i].index === item.index) {
            arr.splice(i, 1);
          }
        }
        return arr;
      }
      state.headTag = filter(state.headTag, router);
      localStorage.router = JSON.stringify(state.headTag);
    }
  },
  getters : {
    getUserMessage(state) {
      if (!state.userMessage) {
        state.userMessage = JSON.parse(localStorage.getItem('userMsg'))
      }
      return state.userMessage
    },
    getHeadTag(state) {
      if(localStorage.getItem('router')) {
        state.headTag = JSON.parse(localStorage.getItem('router'));
        state.closeShow = true;
        return state.headTag;
      }
    }
  },
  actions: {
  },
  modules: {
  }
})
